import useRouteStore from './route'
import useMenuStore from './menu'
import router from '@/router'
import apiUser from '@/api/modules/user'
import { AccountType } from '@/api/modules/types/user'

const useUserStore = defineStore(
  // 唯一ID
  'user',
  () => {
    // const settingsStore = useSettingsStore()
    const routeStore = useRouteStore()
    const menuStore = useMenuStore()
    const passwordRef = ref()

    const account = ref('')
    const userInfo = ref<any>({})
    const token = ref(localStorage.token ?? '')
    const failure_time = ref(localStorage.failure_time ?? '')
    const avatar = ref(localStorage.avatar ?? '')
    const permissions = ref<string[]>([])
    const isLogin = computed(() => {
      let retn = false
      if (token.value) {
        if (new Date().getTime() < new Date(failure_time.value).getTime()) {
          retn = true
        }
      }
      return retn
    })

    async function getUserInfo() {
      try {
        const res = await apiUser.GetAccountInfo()
        const { Account, Token, ExpiresDate } = res
        localStorage.setItem('token', Token)
        localStorage.setItem('failure_time', ExpiresDate)
        // localStorage.setItem('avatar', res.data.avatar)
        account.value = Account.Name
        token.value = Token
        failure_time.value = ExpiresDate
        userInfo.value = Account
      }
      catch (e) {
        console.error(e)
      }
    }

    // 登录
    async function login(data: {
      accountCode: string
      password: string
    }) {
      try {
        const res = await apiUser.login(data)
        const { Account, Token, ExpiresDate } = res
        localStorage.setItem('token', Token)
        localStorage.setItem('failure_time', ExpiresDate)
        // localStorage.setItem('avatar', res.data.avatar)
        account.value = Account.Name
        token.value = Token
        failure_time.value = ExpiresDate
        userInfo.value = Account
      }
      catch (e) {
        console.error(e)
      }
      // avatar.value = res.data.avatar
    }
    // 登出
    async function logout(redirect = router.currentRoute.value.fullPath) {
      localStorage.removeItem('token')
      localStorage.removeItem('failure_time')
      // localStorage.removeItem('avatar')
      account.value = ''
      token.value = ''
      failure_time.value = ''
      avatar.value = ''
      permissions.value = []
      router.push({
        name: 'login',
        // query: {
        //   ...(router.currentRoute.value.path !== settingsStore.settings.home.fullPath && router.currentRoute.value.name !== 'login' && { redirect }),
        // },
      })
      routeStore.removeRoutes()
      menuStore.setActived(0)
      // TODO: 无用代码，后续可删除
      sessionStorage.setItem('redirect', redirect)
    }
    // 获取权限
    async function getPermissions() {
      const res: any = await apiUser.GetAccountPopedomByProgram({ programCode: 'ManageWebProgram' })
      permissions.value = res
      return permissions.value
    }
    // 修改密码
    async function editPassword() {
      passwordRef.value?.open()
    }

    function setPasswordRef(ref: any) {
      passwordRef.value = ref
    }

    const isEnterpris = computed(() => {
      return userInfo.value.AffiliatedObjType === AccountType.Enterpris
    })
    const isEnvOrg = computed(() => {
      return userInfo.value.AffiliatedObjType === AccountType.EnvOrg
    })

    return {
      account,
      token,
      avatar,
      permissions,
      isLogin,
      login,
      logout,
      getPermissions,
      editPassword,
      getUserInfo,
      userInfo,
      setPasswordRef,
      isEnterpris,
      isEnvOrg,
    }
  },
)

export default useUserStore
